<template>
	<!-- 排期剩余情况 -->
	<view class="card">
		<view class="title">
			<view class="title_L">
				<text>维保中电梯保养排期概况</text>
			</view>
		</view>
		<view class="info-view" :style="{ backgroundImage: 'url(' + imageURL + ')' }">
			<view class="info-view-item" @click="changeBg(1)">
				<view class="num">
					{{ d1.value1 }}
					<text>台</text>
				</view>
				<view class="name">已排期电梯</view>
			</view>
			<view class="info-view-item" @click="changeBg(2)">
				<view :class="['num', d1.value2 != 0 ? 'orange' : 'grey']">
					{{ d1.value2 }}
					<text>台</text>
				</view>
				<view class="name">从未排期电梯</view>
			</view>
		</view>
		<view class="title" v-if="tabIdx == 1">
			<view class="title_L">
				<text class="normalTxt">电梯排期剩余情况</text>
				<zb-tooltip arrowLeft="-120" placement="bottom-start" ref="tooltip">
					<image class="msg" src="@/static/images/index/q.png"></image>
					<view class="tipsContent" slot="content">
						<view class=""><text>有剩余排期：</text>已排期电梯在今天及往后日期仍存在</view>
						<view class=""><text></text>排期计划</view>
						<view class=""><text>无剩余排期：</text>已排期电梯在今天及往后日期没有任</view>
						<view class=""><text></text>何排期计划。</view>
					</view>
				</zb-tooltip>
			</view>
		</view>
		<view class="goBlack" v-if="d1.toopText1">
			<view class="left" @click.stop="goCircle()" v-if="tabIdx == 1">
				<view> <text></text> 返回</view>
				<view><text>/</text>{{ d1.toolObj1.name || "" }}</view>
			</view>
			<view class="right" @click.stop="showUploadFile(1, d1.toolObj1.name)"
				v-if="(tabIdx == 1 && d1.value1 != 0) || (tabIdx == 2 && d1.value2 != 0)">
				<image src="@/static/images/download.png" mode="" />
				<view>下载数据</view>
			</view>
		</view>
		<view v-if="d1.toopText1 && tabIdx == 1" class="deepTabs">
			<view @click="changeDeepIdx(0)" :class="{ active: deepIdx === 0 }">按电梯年审类型</view>
			<view @click="changeDeepIdx(1)" :class="{ active: deepIdx === 1 }">按合同到期情况</view>
		</view>
		<view class="charts" @click="cardClose(0)">
			<!-- 缺省 -->
			<view class="empty" v-if="d1.value2 == 0 && tabIdx == 2">
				<view>
					<image src="@/static/images/index/empty1.png"></image>
					<view>暂无内容</view>
				</view>
			</view>
			<l-echart class="ring" ref="d1" v-else-if="!d1.toopText1"></l-echart>
			<l-echart class="ring outside" ref="d1" v-else></l-echart>
			<!-- 数据列表 -->
			<view class="data-lable" v-if="tabIdx == 1">
				<view class="data-lable-item" v-for="(item, index) in d1.chartData.series" :key="index"
					@click="selectLegend(item, 'd1', index)">
					<view class="color"
						:style="{ background: item.show ? d1.toopDesc ? d1.colorsCopy[index] : d1.colorsDeep[index] : '#ccc' }">
					</view>
					<view class="name">{{ item.name }}</view>
					<view class="num">{{ item.eleTotal }}台</view>
					<view class="eleTotal">{{ item.data }}%</view>
				</view>
			</view>
			<!-- 下钻 -->
			<view class="tooltips" v-if="d1.tooplState1">
				<view class="tool_name">{{ d1.toolObj1.pName || "" }}</view>
				<view class="tool_data">
					<view :style="{ background: d1.toolObj1.color || '' }"></view>
					<view>{{ d1.toolObj1.name || "" }}：</view>
					<view>{{ d1.toolObj1.eleTotal || "0" }} ({{ d1.toolObj1.value || "0.0" }}%)</view>
				</view>
				<view class="tool_see" @click="seeClick(d1.toolObj1)" v-if="d1.toolObj1.eleTotal != 0">
					<image src="@/static/images/index/change.png"></image> 下钻
				</view>
			</view>
		</view>
		<view class="goBlack" v-if="(d1.toopText1 && tabIdx == 1) || tabIdx == 2" style="padding-left: 44rpx;">
			<view v-if="d1.toopText1 && tabIdx == 1" style="color: #666666;font-size: 28rpx;">
				<text>{{ d1.toolObj1.name + '总数：' }}</text>
				<text style="color: #333333;font-weight: 500;">{{ d1.toolObj1.eleTotal + '台' }}</text>
			</view>
			<view class="right" @click="toElevatorList"
				v-if="(d1.toolObj1.name && d1.toolObj1.name.indexOf('无剩余排期') != -1) || tabIdx == 2">
				<view class="right" style="color: #0091FF;">
					详情
					<uni-icons color="#0091FF" type="forward" size="14"></uni-icons>
				</view>
			</view>
		</view>
		<view class="descText" v-if="d1.desc && tabIdx == 1">注：若电梯无剩余排期，应根据在保情况及时补充新的排期计划。</view>
		<view class="loading-block" v-if="loading">
			<image class="img" src="@/static/images/loading.png" mode=""></image>
			<view class="text">加载中..</view>
		</view>
		<model :maskClick="false" width="508rpx" :visible="successVisible" title="下载成功" cancleTxt="复制链接"
			comfireTxt="直接打开" @cancle="modelRes(1)" @comfire="modelRes(2)" @close="successVisible = false">
			<view class="modelItem"> 你可以直接打开，或者复制链接至 </view>
			<view class="modelItem"> 电脑端浏览器下载。 </view>
		</model>
	</view>
</template>
<script>
import * as echarts from '@/subpages/components/lime-echart/static/echarts.min';
import { ringOpt, pieLine } from '../utils/chart_opt.js';
import LEchart from '@/subpages/components/lime-echart/components/l-echart/l-echart.vue';
import { getOverview, getScheduleExcel, getNotScheduleExcel } from '@/apis/statistic.js';

import model from '@/components/model/index.vue';
export default {
	name: 'contractTotal',
	components: {
		LEchart,
		model
	},
	data() {
		return {
			// 电梯排期剩余情况
			d1: {
				colorsDeep: ['#5FA9FF', '#7DEBB8'],
				colors: ['#F47D99', '#6FA9FF',],
				colorsCopy: ['#F47D99', '#6FA9FF',],
				count: 0,
				toopDesc: true,
				linedata: {
					categories: [],
					series: [],
				},
				chartData: {
					series: [],
				},
				// tooltip状态
				tooplState1: false,
				// 返回按钮
				toopText1: false,
				desc: false,
				toolObj1: {},
				value1: '',
				value2: '',
			},
			// 导出成功对话框
			successVisible: false,
			// 下载链接
			planMsgUrl: '',
			tempFilePath: '',
			// 已排期和从未排期 区分
			tabIdx: 1,
			imageURL: 'https://000000-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20250804/72d22b8d5946f90a2c1f70aa381a2dfb.png',
			// 脱保电梯总览数据
			loseData: {},
			loading: false,
			downloadUrl: '',
			localPath: '',
			deepIdx: 0, // 下钻查看的类型 0:按电梯年审类型 1:按合同到期情况
			overViewData: {}, // 电梯排期概况数据
			// 下载成功之后弹出框
			// successVisible: false, 
		};
	},
	props: {},
	created() {
		this.getOverview();
	},
	mounted() {

	},
	methods: {
		toElevatorList() {
			uni.navigateTo({
				url: '/subpages/statistics/elevatorList?type=' + (this.tabIdx == 1 ? 4 : 3) + '&deepIdx=' + this.deepIdx,
			});
		},
		changeDeepIdx(type) {
			if (this.deepIdx == type) {
				return;
			}
			this.deepIdx = type;

			this.loading = true;
			// 显示返回按钮
			this.d1.toopText1 = true;

			let obj = this.overViewData || [];
			let cArr = [];
			let objEdit = { state: true, richWidth: 75 };
			let data = {};
			objEdit.type = 'round';
			this.d1.colors = ['#5FA9FF', '#7DEBB8'];
			this.d1.colorsDeep = ['#5FA9FF', '#7DEBB8'];
			// 关闭tooltips
			this.d1.tooplState1 = false;
			if (this.d1.toolObj1.name == '无剩余排期') {
				this.d1.desc = true;
				if (type == 0) {
					data = obj.notFeatureScheduleUseType;
				} else {
					data = obj.notFeatureScheduleMaintainStatus;
				}
			} else if (this.d1.toolObj1.name == '有剩余排期') {
				data = obj.featureScheduleUseType;
				if (type == 0) {
					data = obj.featureScheduleUseType;
				} else {
					data = obj.featureScheduleMaintainStatus;
				}
			} else {
				if (obj.notPlanEleUseType) data = obj.notPlanEleUseType;
			}
			if (type == 0) {
				if (Object.keys(data).length > 1) {
					cArr.push(
						{
							name: '非年审梯',
							eleTotal: data[1].value,
							data: data[1].pct,
							show: true,
						}, {
							name: '年审梯',
							eleTotal: data[0].value,
							data: data[0].pct,
							show: true,
						},);
				} else if (Object.keys(data).length != 0) {
					for (const key in data) {
						const item = data[key];
						if (key == 1) {
							cArr = [{
								name: '非年审梯',
								eleTotal: item.value,
								data: item.pct,
								show: true,
							}];
						} else {
							this.d1.colors.splice(0, 1);
							cArr = [
								{
									name: '年审梯',
									eleTotal: item.value,
									data: item.pct,
									show: true,
								}];
						}
					}
				} else {
					return;
				}
			} else {
				if (Object.keys(data).length != 0) {
					console.log('-----data-----', data);
					for (const key in data) {
						const item = data[key];
						if (key == 2) {
							this.d1.colors = ['#5FA9FF'];
							this.d1.colorsDeep = ['#5FA9FF'];
							cArr.push({
								name: '合同期内',
								eleTotal: item.value,
								data: item.pct,
								show: true,
							});
						} else if (key == 3) {
							this.d1.colors.push('#FBCB92');
							this.d1.colorsDeep.push('#FBCB92');
							cArr.push({
								name: '合同期外',
								eleTotal: item.value,
								data: item.pct,
								show: true,
							});
						} else {
							const keyVal = {
								4: '拟定保养',
								5: '合同终止',
								6: '合同到期',
								7: '下份合同待生效',
							};
							const contractColors = {
								4: '#FF89A8', // 浅天蓝（拟定保养）
								5: '#F28B92', // 樱花粉红（合同终止）
								6: '#FFB74D', // 柑橘橙（合同到期）← 特别优化
								7: '#9575CD', // 薰衣草（下份合同待生效）
								8: '#4DD694', // 春日绿（新状态）
								9: '#FFD54F'  // 阳光黄（紧急状态）
							};
							this.d1.colors.push(contractColors[key] || '#FF89A8');
							this.d1.colorsDeep.push(contractColors[key] || '#FF89A8');
							cArr.push({
								name: keyVal[key] || '未知',
								eleTotal: item.value,
								data: item.pct,
								show: true,
							});
						}
					}
				} else {
					return;
				}
			}
			this['d1'].chartData.series = cArr;
			this.setRingChart('d1', objEdit);
		},
		// 下载成功之后
		modelRes(type) {
			if (type == 1) {
				// 复制
				uni.setClipboardData({
					data: this.downloadUrl,
					success: () => {

					},
				});
				this.successVisible = false;
			} else {
				// #ifdef H5
				// eslint-disable-next-line no-undef
				sida.openUrl({ url: this.downloadUrl });
				// #endif

				// #ifndef H5
				// 直接打开
				uni.openDocument({
					filePath: this.localPath,
					showMenu: true,
					fileType: 'xlsx',
					success: () => {
						console.log('打开文档成功');
					},
					fail: (err) => {
						console.log(err);
					},
				});
				// #endif

				this.successVisible = false;
			}
		},
		// 电梯排期概况
		getOverview() {
			getOverview({}).then(res => {
				this.d1.toopDesc = true;
				this.loading = false;
				const obj = res.data || {};
				this.overViewData = obj;
				let list = [];
				list.push(
					{
						name: '无剩余排期',
						eleTotal: obj.notFeatureScheduleEleCount,
						data: obj.notFeatureScheduleElePct,
						pName: '电梯排期剩余情况',
						show: true
					}, {
						name: '有剩余排期',
						eleTotal: obj.featureScheduleEleCount,
						data: obj.featureScheduleElePct,
						pName: '电梯排期剩余情况',
						show: true
					},);
				// 已排期
				this.d1.value1 = obj.planEleTotal;
				// 从未排期
				this.d1.value2 = obj.notPlanEleTotal;
				let colorsCopy = this.d1.colorsCopy;
				for (let i = 0; i < list.length; i++) {
					if (list[i].eleTotal == 0) {
						this['d1'].colors.splice(this['d1'].colors.indexOf(colorsCopy[i]), 1);
					}
				}
				this.d1.chartData.series = list;
				this.setRingChart('d1',);
			});
		},
		// 点击取消图例
		selectLegend(item, type, index) {
			let list = this[type].chartData.series;
			let colors = this[type].colors;
			item.show = !item.show;
			if (!item.show) {
				colors.splice(index, 1);
			} else {
				colors.splice(index, 0, this[type].colorsCopy[index]);
			}
			let newList = list.filter(e => e.show);
			if (!newList.length) {
				return;
			} else {
				this.setRingChart(type);
			}
		},
		changeBg(idx) {
			this.tabIdx = idx;
			if (idx == 1) {
				this.goCircle();
				this.imageURL = 'https://000000-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20250804/72d22b8d5946f90a2c1f70aa381a2dfb.png';
			} else {
				this.seeClick();
				this.imageURL = 'https://000000-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20250804/5ab0260906077613649a5b0c495a4560.png';
			}
		},
		// 下载数据
		showUploadFile(status, name) {
			uni.showLoading({
				title: '下载中',
				icon: 'none',
			});
			if (status == 1 && this.tabIdx == 1) {
				let type = name == '有剩余排期' ? '0' : '1';
				getScheduleExcel({ type }).then(res => {
					this.downloadUrl = res.data;
					this.submitPlan(res.data);
				});
			} else {
				getNotScheduleExcel().then(res => {
					this.downloadUrl = res.data;
					this.submitPlan(res.data);
				});
			}
		},
		// 下载文件
		submitPlan(url) {
			// #ifdef H5
			// 关闭loading
			sida.openUrl({ url });
			uni.hideLoading();
			// #endif

			// #ifndef H5
			let str = url.split('/')[url.split('/').length - 1];
			uni.downloadFile({
				url,
				filePath: wx.env.USER_DATA_PATH + '/' + str,
				success: (res) => {
					console.log(res, '下载的文件');
					if (res.statusCode === 200) {
						uni.hideLoading();
						this.localPath = res.filePath;
						this.successVisible = true;
						uni.hideLoading();
					}
				},
				fail: () => {
					uni.hideLoading();
				},
			});
			// #endif
		},
		//  点击空白关闭下砖
		cardClose(val) {
			if (val === 0) {
				this.d1.tooplState1 = false;
			}
		},
		// 绘制环形图
		setRingChart(chart, data = {
			click: true
		}) {
			// 绘制环形图
			let list = this[chart].chartData.series;
			let chartData = [];
			for (let i = 0; i < list.length; i++) {
				if (list[i].show && list[i].eleTotal != 0) {
					chartData.push({
						value: list[i].data,
						eleTotal: list[i].eleTotal || '',
						name: list[i].name || '无',
						pName: list[i].pName
					});
				}
			}
			console.log('setRingChart', chart, chartData, this[chart].chartData);
			if (this.tabIdx == 2) {
				this[chart].opts = pieLine({ color: this[chart].colors, data: chartData });
			} else {
				this[chart].opts = ringOpt({ color: this[chart].colors, data: chartData, type: 'ring' });
			}
			this.$nextTick(() => {
				if (!this.$refs[chart]) {
					return;
				}
				this.$refs[chart].init(echarts, chartF => {
					chartF.setOption(this[chart].opts, true);
					chartF.dispatchAction({
						type: 'highlight',
						seriesIndex: 0,
						dataIndex: 0
					});
					chartF.on('legendselectchanged', () => {
						// 处理图例点击导致选中与默认选中重叠问题
						chartF.dispatchAction({ type: 'downplay', seriesIndex: 0 });
					});
					chartF.on('mouseover', (e) => {
						// 当鼠标移除的时候 使默认的索引值去除默认选中
						if (e.dataIndex !== 0) {
							chartF.dispatchAction({ type: 'downplay', dataIndex: 0 });
						}
					});
					chartF.on('click', (e) => {
						setTimeout(() => {
							if (e.data.pName === '电梯排期剩余情况') {
								this.d1.tooplState1 = true;
								this.d1.toolObj1 = { ...e.data, color: e.color };
							}
						}, 100);
					});
				});
				this.loading = false;
			});
		},
		//  下钻查看
		seeClick(objs = {}) {
			this.loading = true;
			this.d1.toopDesc = false;
			// 显示返回按钮
			this.d1.toopText1 = true;

			let obj = this.overViewData || [];
			let cArr = [];
			let objEdit = { state: true, richWidth: 75 };
			let data = {};
			objEdit.type = 'round';
			this.d1.colors = ['#5FA9FF', '#7DEBB8'];
			// 关闭tooltips
			this.d1.tooplState1 = false;
			if (objs.name == '无剩余排期') {
				this.d1.desc = true;
				data = obj.notFeatureScheduleUseType;
			} else if (objs.name == '有剩余排期') {
				data = obj.featureScheduleUseType;
			} else {
				if (obj.notPlanEleUseType) data = obj.notPlanEleUseType;
			}
			if (Object.keys(data).length > 1) {
				cArr.push(
					{
						name: '非年审梯',
						eleTotal: data[1].value,
						data: data[1].pct,
						show: true,
					}, {
						name: '年审梯',
						eleTotal: data[0].value,
						data: data[0].pct,
						show: true,
					},);
			} else if (Object.keys(data).length != 0) {
				for (const key in data) {
					const item = data[key];
					if (key == 1) {
						cArr = [{
							name: '非年审梯',
							eleTotal: item.value,
							data: item.pct,
							show: true,
						}];
					} else {
						this.d1.colors.splice(0, 1);
						cArr = [
							{
								name: '年审梯',
								eleTotal: item.value,
								data: item.pct,
								show: true,
							}];
					}
				}
			} else {
				return;
			}
			this['d1'].chartData.series = cArr;
			this.setRingChart('d1', objEdit);
		},
		//  下钻返回
		goCircle() {
			this.deepIdx = 0; // 回归默认电梯年审类型
			this.d1.desc = false;
			// 显示返回按钮
			this.d1.toopText1 = false;
			this.loading = true;
			this.d1.colors = ['#F47D99', '#6FA9FF',];
			this.getOverview();
		},
	}
};
</script>

<style lang="scss" scoped>
@import './stat.scss';

.card {
	padding: 20rpx 0rpx 20rpx 0;
	width: calc(100% - 40rpx);

	.title {
		padding-left: 20rpx;

		.normalTxt {
			font-weight: normal;
			font-size: 14px;
		}

		.tipsContent {
			text {
				width: 160rpx;
			}
		}
	}

	.goBlack {
		padding: 0 20rpx;
	}

	.descText{
		margin-top: 24rpx;
		margin-left: 22rpx;
	}

	.empty {
		view {
			margin: 0 auto;
		}
	}
}

.deepTabs {
	margin: 20rpx 0;
	display: flex;
	align-items: center;
	padding: 0 20rpx;

	view {
		font-size: 24rpx;
		color: #999;
		margin-right: 24rpx;
	}

	.active {
		color: #333;
		font-weight: bold;
		border-bottom: 2px solid #333;
	}
}

.charts {

	.ring {
		margin-left: 20rpx;
	}

	.outside {
		width: 100% !important;
	}

	.data-lable {
		padding: 0 !important;
		margin-right: 20rpx;
	}
}
</style>